package cn.elead.chaos.remote.web.remote.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.elead.chaos.core.constant.UserConstants;
import cn.elead.chaos.core.enums.BusinessType;
import cn.elead.chaos.excel.ExcelUtil;
import cn.elead.chaos.framework.monitor.operlog.Log;
import cn.elead.chaos.framework.properties.ChaosProperties;
import cn.elead.chaos.framework.util.ChaosUtil;
import cn.elead.chaos.framework.web.global.ApiAssert;
import cn.elead.chaos.framework.web.global.ErrorCodeEnum;
import cn.elead.chaos.framework.web.global.response.UnifiedReturn;
import cn.elead.chaos.mybatils.web.controller.BaseController;
import cn.elead.chaos.mybatils.web.page.TableDataInfo;
import cn.elead.chaos.remote.web.remote.domain.SysUser;
import cn.elead.chaos.remote.web.remote.service.ISysPostService;
import cn.elead.chaos.remote.web.remote.service.ISysRoleService;
import cn.elead.chaos.remote.web.remote.service.ISysUserService;
import cn.elead.chaos.sso.core.util.SsoUtils;
import cn.hutool.core.util.ObjectUtil;

/**
 * 用户信息
 * 
 * @author luopeng
 */
@UnifiedReturn
@RestController
@RequestMapping("/system/user")
public class RemoteUserController extends BaseController {

	@Autowired
	private ISysUserService userService;

	@Autowired
	private ISysRoleService roleService;

	@Autowired
	private ISysPostService postService;

	@Autowired
	private ChaosProperties chaos;

	/**
	 * 获取用户列表
	 */
	@UnifiedReturn
	@GetMapping("/page")
	public TableDataInfo<SysUser> page(SysUser user) {
		startPage();
		List<SysUser> list = list(user);
		return getDataTable(list);
	}

	/**
	 * 获取用户列表
	 */
	@GetMapping("/list")
	public List<SysUser> list(SysUser user) {
		List<SysUser> list = userService.selectUserList(user);
		if (ObjectUtil.isNotEmpty(list)) {
			for (SysUser sysUser : list) {
				sysUser.setPassword("");
				sysUser.setSalt("");
				// sysUser.setCardId("");
				sysUser.setAvatar(ChaosUtil.getAvatarUrl(sysUser.getAvatar()));
			}
		}
		return list;
	}

	@GetMapping("/export")
	@Log(title = "用户管理", businessType = BusinessType.EXPORT)
	public String export(SysUser user) {
		List<SysUser> list = userService.selectUserList(user);
		ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
		return util.exportExcel(list, "用户数据");
	}

	@PostMapping("/importData")
	@Log(title = "用户管理", businessType = BusinessType.IMPORT)
	public String importData(MultipartFile file, boolean updateSupport) throws Exception {
		return null;
	}

	@GetMapping("/importTemplate")
	public String importTemplate() {
		ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
		return util.importTemplateExcel("用户数据");
	}

	/**
	 * 根据用户编号获取详细信息
	 */
	@GetMapping(value = { "/", "/{userId}" })
	public Map<String, Object> getInfo(@PathVariable(value = "userId", required = false) String userId) {
		Map<String, Object> ajax = new HashMap<String, Object>();
		ajax.put("roles", roleService.selectRoleAll());
		ajax.put("posts", postService.selectPostAll());
		if (ObjectUtil.isNotNull(userId)) {
			ajax.put("user", userService.selectUserById(userId));
			ajax.put("postIds", postService.selectPostListByUserId(userId));
			ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
		}
		return ajax;
	}

	/**
	 * 根据用户编号获取详细信息
	 */
	@GetMapping("/info/{userId}")
	public SysUser getSysUser(@PathVariable(value = "userId", required = false) String userId) {
		SysUser sysUser = userService.selectUserById(userId);
		if (ObjectUtil.isNotEmpty(sysUser)) {
			sysUser.setPassword("");
			sysUser.setSalt("");
			// sysUser.setCardId("");
			sysUser.setAvatar(chaos.getHost() + sysUser.getAvatar());
		}
		return userService.selectUserById(userId);
	}

	/**
	 * 根据用户编号获取详细信息
	 */
	@GetMapping("/infos/{userId}")
	public List<SysUser> getInfos(@PathVariable String[] userId) {
		List<SysUser> sysUsers = userService.selectUserByIds(Arrays.asList(userId));
		for (SysUser sysUser : sysUsers) {
			if (ObjectUtil.isNotEmpty(sysUser)) {
				sysUser.setPassword("");
				sysUser.setSalt("");
				// sysUser.setCardId("");
				sysUser.setAvatar(chaos.getHost() + sysUser.getAvatar());
			}
		}
		return sysUsers;
	}

	/**
	 * 新增用户
	 */
	@PostMapping
	@Log(title = "用户管理", businessType = BusinessType.INSERT)
	public int add(@Validated @RequestBody SysUser user) {
		if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("新增用户'" + user.getUserName() + "'失败，登录账号已存在"));
		} else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("新增用户'" + user.getUserName() + "'失败，手机号码已存在"));
		} else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在"));
		}
		user.setCreateBy(SsoUtils.getUserName());
		// user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		return userService.insertUser(user);
	}

	/**
	 * 修改用户
	 */
	@PutMapping
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	public int edit(@Validated @RequestBody SysUser user) {
		userService.checkUserAllowed(user);
		if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("修改用户'" + user.getUserName() + "'失败，手机号码已存在"));
		} else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在"));
		}
		user.setUpdateBy(SsoUtils.getUserName());
		return userService.updateUser(user);
	}

	/**
	 * 删除用户
	 */
	@DeleteMapping("/{userIds}")
	@Log(title = "用户管理", businessType = BusinessType.DELETE)
	public int remove(@PathVariable String[] userIds) {
		return userService.deleteUserByIds(userIds);
	}

	/**
	 * 重置密码
	 */
	@PutMapping("/resetPwd")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	public int resetPwd(@RequestBody SysUser user) {
		userService.checkUserAllowed(user);
		user.setUpdateBy(SsoUtils.getUserName());
		return userService.resetPwd(user);
	}

	/**
	 * 状态修改
	 */
	@PutMapping("/changeStatus")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	public int changeStatus(@RequestBody SysUser user) {
		userService.checkUserAllowed(user);
		user.setUpdateBy(SsoUtils.getUserName());
		return userService.updateUserStatus(user);
	}
}